package com.vote.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.vote.dto.TopicDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.vote.dto.VoteDto;
import com.vote.entity.Topic;
import com.vote.entity.Vote;
import com.vote.service.ITopicService;
import com.vote.service.IVoteService;
import com.vote.vo.ResultEntity;
import com.vote.vo.TopicVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author vote group
 * @since 2020-04-08
 */
@RestController
@RequestMapping("/topic")
public class TopicController {

    @Autowired
    private ITopicService iTopicService;

    @Autowired
    private IVoteService iVoteService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发起一个投票
     * @param topicDto
     * @return
     */
    @RequestMapping("/add")
    public ResultEntity topicAdd(TopicDto topicDto){
        HashOperations hashOperations = redisTemplate.opsForHash();
        topicDto.setCreatedate(new Date());
        //转换成Topic对象
        Topic topic=new Topic();
        BeanUtils.copyProperties(topicDto,topic);
       //添加投票
        iTopicService.insertTopic(topic);
        //查看是否有一对多添加
        if(!StringUtils.isBlank(topicDto.getVoteJson())){
            List<Vote> votes = JSON.parseArray(topicDto.getVoteJson(), Vote.class);
            for (Vote vote : votes) {
                vote.setTid(topic.getTid());
                hashOperations.put(topic.getTid()+"",vote.getOpt(),0);
            }
            iVoteService.insertList(votes);
        }
        return ResultEntity.ok("添加成功");
    }

    /**
     * 查询投票列表
     * @param topicDto
     * @return
     */
    @RequestMapping("/list")
    public ResultEntity topicList(TopicDto topicDto){
        //分页
        PageHelper.startPage(topicDto.getPageNo(),topicDto.getPageSize());
        //添加查询条件
        List<TopicVo> topics = iTopicService.getTopics(topicDto);
        HashOperations hashOperations = redisTemplate.opsForHash();
        for (TopicVo topic : topics) {
            List<Integer> values = hashOperations.values(topic.getTid() + "");
            Integer integer = values.stream().reduce(Integer::sum).orElse(0);
            topic.setNum(integer);
        }
        PageInfo<TopicVo> pageInfo=new PageInfo<>(topics);
        return ResultEntity.ok("查询成功",pageInfo);
    }

    /**
     * 修改投票信息
     * @param topicDto
     * @return
     */
    @RequestMapping("/up")
    public ResultEntity topicUp(TopicDto topicDto){
        HashOperations hashOperations = redisTemplate.opsForHash();
        //转换成Topic对象
        Topic topic=new Topic();
        BeanUtils.copyProperties(topicDto,topic);
        //修改投票
        iTopicService.updateId(topic);
        //修改一对多（先删后加）
        iVoteService.deleteByTid(topic.getTid());
        redisTemplate.delete(topicDto.getTid()+"");
        if(!StringUtils.isBlank(topicDto.getVoteJson())){
            List<Vote> votes = JSON.parseArray(topicDto.getVoteJson(), Vote.class);
            for (Vote vote : votes) {
                vote.setTid(topicDto.getTid());
                if(null!=vote.getNum()&&vote.getNum()!=0){
                    hashOperations.put(topicDto.getTid()+"",vote.getOpt(),vote.getNum());
                }else{
                    hashOperations.put(topicDto.getTid()+"",vote.getOpt(),0);
                }
            }
            iVoteService.insertList(votes);
        }
        return ResultEntity.ok("修改成功");
    }

    /**
     * 删除投票信息
     * @param topicDto
     * @return
     */
    @RequestMapping("/del")
    public ResultEntity topicDel(TopicDto topicDto){
        if(topicDto.getTids().length!=0){
            for (Integer tid : topicDto.getTids()) {
                Wrapper<Vote> wrapper=new EntityWrapper<>();
                wrapper.eq("tid",tid);
                iTopicService.deleteByTid(tid);
                iVoteService.deleteByTid(tid);
                redisTemplate.delete(tid+"");
            }
        }
        return ResultEntity.ok("删除成功");
    }

    /**
     * 设置首页显示的数据
     * @param topicDto
     * @return
     */
    @RequestMapping("/default")
    public ResultEntity deFault(TopicDto topicDto){
        redisTemplate.opsForValue().set("topicdefault",topicDto.getTid());
        return ResultEntity.ok("设置成功");
    }

}
